package com.css.config.netty.message;

import com.css.config.netty.IoSession;
import com.css.config.netty.enums.PacketType;
import io.netty.buffer.ByteBuf;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;

/**
 * 抽象消息定义
 * @author
 */
public abstract class AbstractPacket extends ByteBufBean {

	Logger logger = LoggerFactory.getLogger(this.getClass());

	abstract public PacketType getPacketType();

	/**
	 * 业务处理
	 */
	abstract public void execPacket(IoSession session);

	/**
	 *  是否开启gzip压缩(默认关闭)
	 *  消息体数据大的时候才开启，非常小的包压缩后体积反而变大，而且耗时
	 */
	public boolean isUseCompression() {
		return false;
	}

	public FileUpload readFile(ByteBuf buf){

		try {

			int fileNameInt = buf.readInt();
			byte[] fileNameByte = new byte[fileNameInt];
			buf.readBytes(fileNameByte);
			String fileNameStr = new String(fileNameByte,"UTF-8");

			int fileTypeInt = buf.readInt();
			byte[] fileTypeByte = new byte[fileTypeInt];
			buf.readBytes(fileTypeByte);
			String fileTypeStr = new String(fileTypeByte,"UTF-8");

			//int startPos = buf.readInt();

			int countByteInt = buf.readInt();
			byte[] countByte = new byte[countByteInt];
			buf.readBytes(countByte);

			//int endPos = buf.readInt();

			int base64Int = buf.readInt();
			byte[] base64Byte = new byte[base64Int];
			buf.readBytes(base64Byte);
			String base64Str = new String(base64Byte,"UTF-8");

			FileUpload fileUpload = new FileUpload();
			fileUpload.setBytes(countByte);
			//fileUpload.setEndPos(endPos);
			fileUpload.setFileName(fileNameStr);
			fileUpload.setFileType(fileTypeStr);
			fileUpload.setBase64Str(base64Str);
			//fileUpload.setStarPos(startPos);

			return fileUpload;
		}catch (Exception e){
			logger.error("读取文件失败",e);
		}

		return null;

	}

	/**
	 * @Description: 写文件
	 * @Param: [buf, fileUpload]
	 * @return: void
	 * @Author: zyj
	 * @Date: 2020/3/2
	 */
	protected  void writeFile(ByteBuf buf, FileUpload fileUpload){

		try {
			byte[] fileName = fileUpload.getFileName().getBytes("UTF-8");
			buf.writeInt(fileName.length);
			buf.writeBytes(fileName);

			byte[] fileType = fileUpload.getFileType().getBytes("UTF-8");
			buf.writeInt(fileType.length);
			buf.writeBytes(fileType);

			byte[] count = fileUpload.getBytes();
			buf.writeInt(count.length);
			buf.writeBytes(count);

			byte[] base64Count = fileUpload.getBase64Str().getBytes("UTF-8");
			buf.writeInt(base64Count.length);
			buf.writeBytes(base64Count);
			logger.debug("文件数据编码成功");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			logger.debug("文件数据编码失败");
		}
	}

}
